<?php
namespace app\api\controller\v1\model\IM;

use think\Model;
use think\Db;
use RongCloud;

//use think\response\Redirect;
//include_once EXTEND_PATH.'RongCloud/API/methods/User.php';
include_once EXTEND_PATH.'RongCloud/API/rongcloud.php';


class IM extends Model
{
    //显示用户的头像跟昵称
    public function get_User_Info($user_id)
    {
        $result = Db::query("select small_user_icon, user_name from user_info where user_id = '$user_id'");
        return $result;
    }

    //显示医生的头像跟昵称
    public function get_Doctor_Info($doctor_id)
    {
        $result = DB::name('doctor_user')->where('doctor_id','=',$doctor_id)->field(['doctor_small_icon', 'doctor_name', 'rc_token'])->find();
        return $result;
    }

    /**
     * 获取用户融云token
     * @param  integer $user_id 用户id
     * @return boolear      操作是否成功
     */
    public function get_IM_Token($user_id)
    {
        $im = new IM();
        $result = $im->get_User_Info($user_id);
        $data = [
            'user_id' => $user_id,
            'type' => 1
        ];
        if (!$result) {
            //用户获取失败
            return false;
        }
        //判断数据是否存在数据库
        $is_exist = DB::name('ym_token')->where('user_id', '=', $user_id)->value('rc_token');
        if ($is_exist) {
            $data['rc_token'] = $is_exist;
            return $data;
        }
        // 实例化融云类
        $RongCloud = self::get_rongcloud_instance();
        // 获取token
        $token_json = $RongCloud->User()->getToken($user_id, $result[0][user_name], "api/public" . $result[0][small_user_icon]);
        $token_array = json_decode($token_json, true);
        // 获取token失败
        if ($token_array['code'] != 200) {
            return false;
        }
        $token = $token_array['token'];
        $data['rc_token'] = $token;
        /*插入数据库*/
        $sdata = [
            'user_id' => $user_id,
            'rc_token' => $token
        ];
        $res = $im->insert_user_token($sdata);
        return $data;
    }

    /**
     *  获取医生融云token
     */
    public function get_Doctor_IM_Token($id)
    {
        $im = new IM();
        $result = $im->get_Doctor_Info($id);
        if (!$result) {
            //用户获取失败
            return false;
        }
        $doctor_id = "doctor_".$id;
        $data = [
            'doctor_id' => $doctor_id,
            'type' => 2,
        ];
        //判断数据是否存在数据库
        $is_exist = $result['rc_token'];
        if ($is_exist) {
            $data['rc_token'] = $is_exist;
            return $data;
        }
        // 实例化融云类
        $RongCloud = self::get_rongcloud_instance();
        $token_json = $RongCloud->User()->getToken($doctor_id, $result[doctor_name], "api/public" . $result[doctor_small_icon]);
        $token_array = json_decode($token_json, true);
        // 获取token失败
        if ($token_array['code'] != 200) {
            return false;
        }
        $token = $token_array['token'];
        $data['rc_token'] = $token;
        //插入数据库
        $sdata = [
            'doctor_id' => $id,
            'rc_token' => $token
        ];
        $res = $im->update_doctor_token($sdata);
        return $data;
    }

    /**
     * 更新融云头像
     * @param  integer $uid 用户id
     * @return boolear      操作是否成功
     */
    public function refresh_rongcloud_info($user_id)
    {
        // 获取用户昵称和头像
        $user_data = DB::name('user_info')->field('user_name,user_icon')->where('user_id', '=', $user_id)->find();
        // 用户不存在
        if (empty($user_data)) {
            return false;
        }
        // 实例化融云类
        $RongCloud = self::get_rongcloud_instance();
        // 更新融云用户头像
        $result_json = $RongCloud->User()->refresh($user_id, $user_data['user_name'], $user_data['user_icon']);
        $result_array = json_decode($result_json, true);
        if ($result_array['code'] == 200) {
            $del_token = DB::name('ym_token')->where('user_id', '=', $user_id)->delete();
            return true;
        } else {
            return false;
        }
    }

    /**
     * 查找在线医生接口
     * @return bool|mixed|string
     */
    public function get_roll_doctor()
    {
        //查找数据库在线医生，同时对比查找融云在线id
        try{
            $data = '';
            $result = DB::name('doctor_user')->where('login_status','=',1)->field(['doctor_id','doctor_name','doctor_small_icon'])->select();
            // 实例化融云类
            $RongCloud = self::get_rongcloud_instance();
            while($result)
            {
                $num = rand(0,count($result)-1);
                $in_login = $RongCloud->user()->checkOnline('doctor_'.$result[$num]['doctor_id']);
                $in_login = json_decode($in_login, true);
                //检查在线医生是否在融云上也是在线的
                if($in_login['status'] == 1)
                {
                    $data = $result[$num];
                    break;
                }else{
                    unset($result[$num]);
                }
            }
            //找到医生 为医生问诊次数加一
            if(!empty($data))
            {
                $add_inq = DB::name('doctor_user')->where('doctor_id',$data['doctor_id'])->setInc('num_of_inq');
            }
            return $data;
        }catch(\Exception $e){
            echo $e->getMessage();
            return false;
        }
    }

    /**
     * 查询医生端问诊总数
     * @return array 状态值和问诊总数
     */
    public function get_inquisition_count()
    {
        try {
            $count = Db::name('doctor_user')->sum('num_of_inq');
            return ['status'=>true,'data'=>$count];
        }catch(\Exception $e) {
            echo $e->getMessage();
            return ['status'=>false,'data'=>$e->getMessage()];
        }

    }

    /**
     * 加入黑名单
     * @param $user_id
     * @param $target_id
     * @param $type
     * @return bool
     */
    public function blacklist_add($user_id, $target_id, $type)
    {
        $result = '';
        // 实例化融云类
        $RongCloud = self::get_rongcloud_instance();
        // 加入黑名单
        if($type == 1) {
            $result = $RongCloud->user()->addBlacklist($user_id, $target_id);
        }else if($type == 2) {
            $result = $RongCloud->user()->addBlacklist('doctor_'.$user_id, $target_id);
        }else {
        }
        $resutl = json_decode($result, true);
        //判断是否成功
        if($resutl['code'] == 200 )
        {
            return true;
        }
        return false;
    }

    /**
     * 获取用户黑名单
     * @param $user_id
     * @param $type
     * @return
     */
    public function blacklist_get($user_id, $type)
    {
        $result = '';
        // 实例化融云类
        $RongCloud = self::get_rongcloud_instance();
        // 获取黑名单
        if($type == 1) {
            $result = $RongCloud->user()->queryBlacklist($user_id);;
        }else if($type == 2) {
            $result = $RongCloud->user()->queryBlacklist('doctor_'.$user_id);
        }else {
        }
        $resutl = json_decode($result, true);
        //判断是否成功
        if($resutl['code'] == 200 )
        {
            return ['status'=>true,'data'=>$resutl['users']];
        }
        return ['status'=>false];
    }

    /**
     * 删除黑名单成员
     * @param $user_id
     * @param $target_id
     * @param $type
     * @return bool
     */
    public function blacklist_delete($user_id, $target_id, $type)
    {
        $result = '';
        // 实例化融云类
        $RongCloud = self::get_rongcloud_instance();
        // 删除黑名单用户
        if($type == 1) {
            $result = $RongCloud->user()->removeBlacklist($user_id, $target_id);
        }else if($type == 2) {
            $result = $RongCloud->user()->removeBlacklist('doctor_'.$user_id, $target_id);
        }else {
        }
        $resutl = json_decode($result, true);
        //判断是否成功
        if($resutl['code'] == 200 )
        {
            return true;
        }
        return false;
    }

    /**
     * 获取融云实例
     * @param  null
     * @return array    包含key和secret
     */
    private static function get_rongcloud_instance()
    {
        $data = [
            "key" => "m7ua80gbmjhkm",
            "secret" => "j3XGz5YTjYs",
        ];
        $rongcloud = new RongCloud($data['key'], $data['secret']);
        return $rongcloud;
    }

    /**
     *  存入用户token
     */
    public function insert_user_token($data)
    {
        $result = DB::name('ym_token')->insert($data);
        return $result;
    }

    /**
     *  更新医生token
     * @param $data
     * @return int|string
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function update_doctor_token($data){
        $result = DB::name('doctor_user')->where('doctor_id','=',$data['doctor_id'])->update($data);
        return $result;
    }




}